import { Effect } from 'umi';
import { message } from 'antd';
import { fetchAllAppNotPage } from '@/services/app';
import { querySysDict } from '@/services/system';
import { fetchAllTask} from '@/services/task';
import { fetchAllTrade } from '@/services/trade';
import { fetchUsersByRole } from '@/services/user';
import { queryCqUndoTaskList,
  queryTradeUndoTaskList,
  fillCqDetailInfo,
  fillCqDocInfo,
  cqAddTrade,
  cqDeleteTrade,
  preAllocTradeTask,
  updateTradeTask,
  deleteTradeTask,
  allotCqTrade, developerHandleTask, testerHandleTask, auditorHandleTask, 
  designerHandleTask, importTradeTask } from '@/services/workbench';
import { DataItem, TradeResult } from '@/types/global';
import { TradeItem } from '@/types/trade';
import { CqUndoTaskType, TradeUndoTaskType } from '@/types/workbench';
import { BaseModelType } from './common';


export interface WorkbenchModelState {
  cqUndoTaskList: CqUndoTaskType[];
  tradeUndoTaskList: TradeUndoTaskType[];
  // 需求待办任务总数
  cqUndoTaskNum: number;
  // 交易待办任务总数
  tradeUndoTaskNum: number;
  // 今日已完成需求任务总数
  todayCqDoTaskNum: number;
  // 今日已完成交易任务总数
  todayTradeDoTaskNum: number;
  cqTaskTotal: number;
  tradeTaskTotal: number;
  cqTaskCurrentPageNum: number,
  tradeTaskCurrentPageNum: number,
  pageSize: number;
  tradeList: TradeItem[];
  cqUndoTaskTypeData: DataItem[];
  tradeUndoTaskTypeData: DataItem[];
}

export interface WorkbenchModelType extends BaseModelType {
  namespace: 'workbenchs';
  state: WorkbenchModelState;
  effects: {
    fetchWorkbenchInitParams: Effect;
    queryCqUndoTaskList: Effect;
    queryTradeUndoTaskList: Effect;
    fetchCqDetailInitParams: Effect;
    fillCqDetailInfo: Effect;
    fetchCqDocInitParams: Effect;
    fillCqDocInfo: Effect;
    fetchCqTradeInitParams: Effect;
    cqAddTrade: Effect;
    cqDeleteTrade: Effect;
    fetchTradeTasks: Effect;
    preAllocTradeTask: Effect;
    updateTradeTask: Effect;
    deleteTradeTask: Effect;
    allotCqTrade: Effect;
    handleTradeTask: Effect;
    importTradeTask: Effect;
    unMount: Effect;
  };
}

const WorkbenchModel: WorkbenchModelType = {
  namespace: 'workbenchs',

  state: {
    cqUndoTaskList: [],
    tradeUndoTaskList: [],
    cqUndoTaskNum: 0,
    tradeUndoTaskNum: 0,
    todayCqDoTaskNum: 0,
    todayTradeDoTaskNum: 0,
    cqTaskTotal: 0,
    tradeTaskTotal: 0,
    cqTaskCurrentPageNum: 1,
    tradeTaskCurrentPageNum: 1,
    pageSize: 10,
    tradeList: [],
    cqUndoTaskTypeData: [
      {
        key: '1',
        value: '录入详细信息'
      },
      {
        key: '2',
        value: '录入文档信息'
      },
      {
        key: '3',
        value: '分配交易任务'
      }
    ],
    tradeUndoTaskTypeData: [
      {
        key: '1',
        value: '确认开发'
      },
      {
        key: '2',
        value: '确认测试'
      },
      {
        key: '3',
        value: '确认审查'
      },
      {
        key: '4',
        value: '确认设计'
      },
    ]
  },

  effects: {
    *fetchWorkbenchInitParams({ payload }, sagaEffects) {
      const { all, call, put } = sagaEffects;
      try {
        const [ systemResponse, clusterResponse, statusResponse ] = yield all([
          call(querySysDict, {
            dictName: 'system'
          }),
          call(querySysDict, {
            dictName: 'cluster'
          }),
          call(querySysDict, {
            dictName: 'status'
          })
        ]);
        console.info(systemResponse);
        console.info(clusterResponse);
        console.info(statusResponse);
        const systemSuccess =  systemResponse.success;
        const clusterSuccess =  clusterResponse.success;
        if (systemSuccess && clusterSuccess) {
          const result  = {
            systemData: [...systemResponse.result],
            clusterData: [...clusterResponse.result],
          };
          console.info(result);
          yield put({ type: 'systems/updateState', payload: result });
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *queryCqUndoTaskList({ payload }, sagaEffects) {
      const { call, put } = sagaEffects;
      try {
        const response: TradeResult = yield call(queryCqUndoTaskList, payload);
        const { success } = response;
        if (success) {
            // 通讯成功取出数据
            const { result } = response;
            // 模拟延迟3秒
            // yield call(delay, 3000);
            // 更新数据
            const { cqUndoTaskNum, cqUndoTaskList, todayCqDoneTaskNum} = result;
            const payload = {
              cqUndoTaskNum,
              cqUndoTaskList,
              todayCqDoneTaskNum
            }
            yield put({ type: 'updateState', payload });
        } else {
            message.error(`${response.errorCode}:${response.errorMsg}`); // 打印错误信息
        }
      } catch(e) {
        console.info(e);
        message.error('数据获取失败'); // 打印错误信息
      }
    },
    *queryTradeUndoTaskList({ payload }, sagaEffects) {
      const { call, put } = sagaEffects;
      try {
        const response: TradeResult = yield call(queryTradeUndoTaskList, payload);
        const {success} = response;
        if (success) {
          // 通讯成功取出数据
          const {result} = response;
          // 更新数据
          const { tradeUndoTaskNum } = result;
          // 存在交易待办任务，则查询用户数据
          if (tradeUndoTaskNum > 0) {
            const { all } = sagaEffects;
            const [ developerResponse, testerResponse ] = yield all([
              call(fetchUsersByRole, {
                roleCode: 'developer'
              }),
              call(fetchUsersByRole, {
                roleCode: 'tester'
              }),
            ]);
            const devSuccess =  developerResponse.success;
            const testSuccess =  testerResponse.success;
            if (devSuccess && testSuccess) {
              const userResult  = {
                ...developerResponse.result,
                ...testerResponse.result,
              };
              console.info(userResult);
              yield put({ type: 'users/updateState', payload: userResult });
            }
          }
          const { tradeUndoTaskList, todayTradeDoneTaskNum } = result;
          const payload = {
            tradeUndoTaskNum,
            tradeUndoTaskList,
            todayTradeDoneTaskNum
          };
          yield put({ type: 'updateState', payload });
        } else {
          // 打印错误信息
          message.error(`${response.errorCode}:${response.errorMsg}`);
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *fetchCqDetailInitParams({ payload }, sagaEffects) {
      // 先判断会话中是否有缓存
      // 若有则取会话缓存，没有则服务端获取
      const { all, call, put } = sagaEffects;
      try {
        const [ designerResponse, auditorResponse, systemResponse, clusterResponse, appListResponse ] = yield all([
          call(fetchUsersByRole, {
            roleCode: 'designer'
          }),
          call(fetchUsersByRole, {
            roleCode: 'auditor'
          }),
          call(querySysDict, {
            dictName: 'system'
          }),
          call(querySysDict, {
            dictName: 'cluster'
          }),
          call(fetchAllAppNotPage, {})
        ]);
        // console.info(designerResponse);
        // console.info(auditorResponse);
        const designerSuccess =  designerResponse.success;
        const auditorSuccess =  auditorResponse.success;
        const systemSuccess =  systemResponse.success;
        const clusterSuccess =  clusterResponse.success;
        const appListSuccess =  appListResponse.success;
        if (designerSuccess && auditorSuccess && systemSuccess && clusterSuccess && appListSuccess) {
          const result1  = {
            ...designerResponse.result,
            ...auditorResponse.result,
          };
          yield put({ type: 'users/updateState', payload: result1 });
          const result2  = {
            systemData: [...systemResponse.result],
            clusterData: [...clusterResponse.result],
          };
          yield put({ type: 'systems/updateState', payload: result2 });
          const result3 = {
            appList: [...appListResponse.result!.appList],
          };
          yield put({ type: 'cqs/updateState', payload: result3 });
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *fillCqDetailInfo({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(fillCqDetailInfo, payload);
        const { success } = response;
        if (success) {
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('录入失败');
        return false;
      }
    },
    *fetchCqDocInitParams({ payload }, sagaEffects) {
      // 先判断会话中是否有缓存
      // 若有则取会话缓存，没有则服务端获取
      const { all, call, put } = sagaEffects;
      try {
        const [ designerResponse, auditorResponse, systemResponse, clusterResponse, appListResponse ] = yield all([
          call(fetchUsersByRole, {
            roleCode: 'designer'
          }),
          call(fetchUsersByRole, {
            roleCode: 'auditor'
          }),
          call(querySysDict, {
            dictName: 'system'
          }),
          call(querySysDict, {
            dictName: 'cluster'
          }),
          call(fetchAllAppNotPage, {})
        ]);
        console.info(designerResponse);
        console.info(auditorResponse);
        const designerSuccess =  designerResponse.success;
        const auditorSuccess =  auditorResponse.success;
        const systemSuccess =  systemResponse.success;
        const clusterSuccess =  clusterResponse.success;
        const appListSuccess =  appListResponse.success;
        if (designerSuccess && auditorSuccess && systemSuccess && clusterSuccess && appListSuccess) {
          const result1  = {
            ...designerResponse.result,
            ...auditorResponse.result,
          };
          yield put({ type: 'users/updateState', payload: result1 });
          const result2  = {
            systemData: [...systemResponse.result],
            clusterData: [...clusterResponse.result],
          };
          yield put({ type: 'systems/updateState', payload: result2 });
          const result3 = {
            appList: [...appListResponse.result!.appList],
          };
          yield put({ type: 'cqs/updateState', payload: result3 });
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *fillCqDocInfo({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(fillCqDocInfo, payload);
        const { success } = response;
        if (success) {
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('录入失败');
        return false;
      }
    },
    *fetchCqTradeInitParams({ payload }, sagaEffects) {
      // 先判断会话中是否有缓存
      // 若有则取会话缓存，没有则服务端获取
      const { all, call, put } = sagaEffects;
      try {
        // 查询是否已分配交易
        // 查询交易列表
        const [ auditorResponse, developerResponse, testerResponse, tradeTaskNameResponse, allTradeResponse ] = yield all([
          call(fetchUsersByRole, {
            roleCode: 'auditor'
          }),
          call(fetchUsersByRole, {
            roleCode: 'developer'
          }),
          call(fetchUsersByRole, {
            roleCode: 'tester'
          }),
          call(querySysDict, {
            dictName: 'tradeTaskName'
          }),
          call(fetchAllTrade, payload),
        ]);
        const auditorSuccess =  auditorResponse.success;
        const developerSuccess =  developerResponse.success;
        const testerSuccess =  testerResponse.success;
        const allTradeSuccess =  allTradeResponse.success;
        const tradeTaskNameSuccess =  tradeTaskNameResponse.success;
        if (auditorSuccess && developerSuccess && testerSuccess && allTradeSuccess && tradeTaskNameSuccess) {
          const result1  = {
            ...auditorResponse.result,
            ...developerResponse.result,
            ...testerResponse.result,
          };
          yield put({ type: 'users/updateState', payload: result1 });
          const result2 = allTradeResponse.result;
          const { rows } = result2;
          if (rows) {
            yield put({ type: 'updateState', payload: {
              tradeList: [...rows]
            }});
          }
          const result3  = {
            tradeTaskNameData: [...tradeTaskNameResponse.result],
          };
          yield put({ type: 'systems/updateState', payload: result3 });
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *cqAddTrade({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(cqAddTrade, payload);
        const { success } = response;
        if (success) {
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('添加失败');
        return false;
      }
    },
    *cqDeleteTrade({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(cqDeleteTrade, payload);
        const { success } = response;
        if (success) {
          return true;
        }
        return false;
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('添加失败');
        return false;
      }
    },
    *fetchTradeTasks({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(fetchAllTask, payload);
        const { success } = response;
        if (success) {
          // 通讯成功取出数据
          const { result } = response;
          return result;
        }
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('数据获取失败');
        return false;
      }
    },
    *preAllocTradeTask({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(preAllocTradeTask, payload);
        const { success } = response;
        if (success) {
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('新增交易任务失败');
        return false;
      }
    },
    *updateTradeTask({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(updateTradeTask, payload);
        const { success } = response;
        if (success) {
          return true;
        }
        return false;
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('更新交易任务失败');
        return false;
      }
    },
    *deleteTradeTask({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(deleteTradeTask, payload);
        const { success } = response;
        if (success) {
          return true;
        }
        return false;
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('删除交易任务失败');
        return false;
      }
    },
    *allotCqTrade({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response = yield call(allotCqTrade, payload);
        const { success } = response;
        if (success) {
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('录入失败');
        return false;
      }
    },
    *handleTradeTask({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        // 1 2 3 4
        const { status } = payload;
        // 不同的状态，不同的服务
        let response: TradeResult;
        if (status === '1') {
          response = yield call(developerHandleTask, payload);
        } else if (status === '2') {
          response = yield call(testerHandleTask, payload);
        } else if (status === '3') {
          response = yield call(auditorHandleTask, payload);
        } else {
          response = yield call(designerHandleTask, payload);
        }
        const { success } = response;
        if (success) {
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        // 打印错误信息
        message.error('交易任务处理失败');
        return false;
      }
    },
    *importTradeTask({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(importTradeTask, payload);
        // console.log(JSON.stringify(response));
        // yield call(delay, 3000);
        const { success } = response;
        if (success) {
          message.success('批量导入成功，可勾选交易查看具体任务');
          // 刷新表格
          return true;
        } else {
          message.error('批量导入失败，请联系管理员');
          return false;
        }
      } catch(e) {
        console.error(e);
        message.error('批量导入失败，请联系管理员'); // 打印错误信息
        return false;
      }
    },
    *unMount({ payload }, sagaEffects) {
      const { put } = sagaEffects;
      const result = {
        cqTaskList: [],
        tradeTaskList: [],
        cqUndoTaskNum: 0,
        tradeUndoTaskNum: 0,
        todayCqDoTaskNum: 0,
        todayTradeDoTaskNum: 0,
        cqTaskTotal: 0,
        tradeTaskTotal: 0,
        activeKey: 'cqTask',
        tradeTaskModalVisible: false,
        tradeTaskModalTitle: '',
        formData: [],
        taskType: '',
        pageSize: 10,
        cqTaskCurrentPageNum: 1,
        tradeTaskCurrentPageNum: 1,
        tradeList: [],
      }
      yield put({ type: 'updateState', payload: result });
    }
  },

  reducers: {
    updateState(state, { payload }) {
      console.info(payload);
      return {
        ...state,
        ...payload
      }
    },
  },
}

export default WorkbenchModel;